package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class DemoFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token=request.getHeader("token");
        if (token==null|| token.isEmpty()){
            log.info("用户未登录");
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer id = (Integer) claims.get("id");
            CurrentHolder.setCurrentId(id);
            log.info("当前用户id为：{}",id);
        } catch (Exception e) {
            log.info("token被篡改");
            response.setStatus(403);
            return;
        }
        log.info("token没问题");
        filterChain.doFilter(servletRequest, servletResponse);
        CurrentHolder.remove();
    }
}
